﻿using System.Threading;

namespace 四
{
    public class WeatherData : EventArgs
    {
        public DateTime Time { get; set; }
        public int Temperature { get; set; }
        public int Humidity { get; set; }
    }

    public class WeatherStation
    {
        public event EventHandler<WeatherData> NewData;

        private readonly object _lock = new object();
        public WeatherData CurrentData { get; private set; }

        public WeatherStation()
        {
            CurrentData = new WeatherData
            {
                Time = DateTime.Now,
                Temperature = 0,
                Humidity = 0
            };
        }

        public void GetNewData(int temperature, int humidity)
        {
            lock (_lock)
            {
                CurrentData.Time = DateTime.Now;
                CurrentData.Temperature = temperature;
                CurrentData.Humidity = humidity;
                OnNewData();
            }
        }

        private void OnNewData()
        {
            NewData?.Invoke(this, CurrentData);
        }
    }

    public class ScreenDisplay
    {
        public void OnNewData(object sender, WeatherData data)
        {
            Console.WriteLine("_________________________________________");
            Console.WriteLine($"时间：{data.Time}，温度：{data.Temperature}，湿度：{data.Humidity}");
            Console.WriteLine("_________________________________________");
            Console.WriteLine();
        }
    }

    public class DatabaseSaver
    {
        public void OnNewData(object sender, WeatherData data)
        {
            Console.WriteLine("_________________________________________");
            Console.WriteLine($"数据库保存：时间{data.Time}的数据！");
            Console.WriteLine("_________________________________________");
            Console.WriteLine();
        }
    }

    public class WeatherTest
    {
        private readonly WeatherStation _station = new WeatherStation();
        private readonly ScreenDisplay _screen = new ScreenDisplay();
        private readonly DatabaseSaver _db = new DatabaseSaver();
        private readonly Random _rnd = new Random();
        private Timer _timer;

        public WeatherTest()
        {
            _station.NewData += _screen.OnNewData;
            _station.NewData += _db.OnNewData;
        }

        public void StartTest()
        {
            _timer = new Timer(OnTimerElapsed, null, 0, 3000);
            Console.ReadLine();
            _timer.Dispose();
        }

        private void OnTimerElapsed(object state)
        {
            _station.GetNewData(
                _rnd.Next(-10, 35),
                _rnd.Next(30, 90)
            );
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            WeatherTest test = new WeatherTest();
            test.StartTest();
        }
    }
}
